//
//  BBEPictureViewController.swift
//  PictureShow
//
//  Created by apple on 16/4/27.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

private let reuseIdentifier = "cell"

class BBEPictureViewController: UICollectionViewController {
    
    lazy var dataArray :[BBEPictureModel] = [BBEPictureModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView?.backgroundColor = UIColor.grayColor()
     
        data(0)
    }

}

// 发送网络请求
extension BBEPictureViewController {
    func data(offset : Int)
    {
        let net = BBENetWorkTool.shareNetworking
        
        let dict = ["offset" : "\(offset)",
            "limit" : "30",
            "access_token" : "b92e0c6fd3ca919d3e7547d446d9a8c2"
        ]
        
        net.requestData("http://mobapi.meilishuo.com/2.0/twitter/popular.json", parameter: dict) { (result, error) -> Void in
            
            if result == nil {
                return
            }
            
            guard let result = result else{
                return
            }
            
            for dictionary in result["data"] as! [[String : NSObject]]{
                let model = BBEPictureModel(dict: dictionary)
                
                self.dataArray.append(model)
            }
            self.collectionView?.reloadData()
        }
        
    }
}

extension BBEPictureViewController {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
       let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! BBECollectionViewCell
        
        cell.pictureModel = dataArray[indexPath.item]
        
        
        if indexPath.item == dataArray.count - 1 {
            self.data(dataArray.count)
        }
        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let showVC = BBEShowViewController()
        showVC.view.backgroundColor = UIColor.redColor()
        self.presentViewController(showVC, animated: true , completion: nil)
           }
}